//
//  YQChatViewController.swift
//  yq微信
//
//  Created by Me yq on 2017/9/29.
//  Copyright © 2017年 yq. All rights reserved.
//

import UIKit
class YQChatViewController: UIViewController,UITableViewDelegate,UITableViewDataSource,UITextFieldDelegate{
    
    // 重用ID
    let ID = String(describing:self)
    var buddy : String? = nil
    
    // （新）消息容器
    var chatMsgs:NSMutableArray = {
        
        let  _chatMsgs:NSMutableArray? = NSMutableArray()
        
        return _chatMsgs!
    }()
    
    // 自定义一个输入框view
    lazy var chatView : YQChattView? = {
        
        let chattView = YQChattView.yq_createChatView()
        chattView.textField.delegate = self
        
        // chatView布局
        let chatInputH : CGFloat = 40
        let chatInputY =  screenH - chatInputH
        chattView.frame = CGRect(x: 0, y: chatInputY, width: screenW, height: chatInputH)
        return chattView
    }()
   
    // 懒加载 tableview (子控件)
    lazy var tableView:UITableView? = {
        
        let tableView = UITableView()
        // test
//      tableView.backgroundColor = UIColor.green
        let x:CGFloat = 0
        let y:CGFloat = 0
        let width  = screenW
        let height = self.chatView?.frame.origin.y
        tableView.frame = CGRect(x: x, y: y, width: width, height: height!)
        
        tableView.delegate = self
        tableView.dataSource = self

        // Btn
        let frame =  tableView.frame
        let btn = UIButton(frame: frame )
        btn.backgroundColor = UIColor.clear
        tableView.addSubview(btn)
        btn.addTarget(self  , action: #selector(btnclick ), for: .touchDown)
        return tableView
    }()
  
    //MARK:系统回调
    override func viewDidLoad() {
        super.viewDidLoad()
        self.tableView?.allowsSelection = false
        
        self.view.backgroundColor = UIColor.blue
        self.title  = self.buddy!
       
        // 自定义inputView
        self.addChatView(self.chatView!)
        self.addTableView(self.tableView!)

        self.yq_reloadChatMessages()
        self.yq_addKeyboardObserver()
        
        // register cell
        self.tableView?.separatorStyle = .none
        self.tableView?.register(YQChatCell.self , forCellReuseIdentifier: ID)
        self.tableView?.backgroundColor = K243Color
        
        
        // 添加代理,监听收到消息
        EMClient.shared().chatManager.add(self, delegateQueue: DispatchQueue.main)
        
    }
   
    //MARK: tabbar显示/隐藏
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        self.tabBarController?.tabBar.isHidden = true
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        // 隐藏控制器，显示tabbar
//      self.navigationController?.tabBarController?.tabBar.isHidden = false
        self.tabBarController?.tabBar.isHidden = false
    }
    
    //FIXME: 解决第一次进入界面没有滚动到底部
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        self.scrollToBottom(self.tableView!, animated: false)
    }
    
    // 行数
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
      
        print("chatMsgs.count:\(self.chatMsgs.count)")
        return self.chatMsgs.count
    }
    
    // 每行所显示的内容
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
      
        let  cell : YQChatCell? = tableView.dequeueReusableCell(withIdentifier:ID ) as? YQChatCell
        cell?.chatFrame = self.chatMsgs[indexPath.row] as? YQChatFrame
        return cell!
    }

    // 行高
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {

        let chatFrame:YQChatFrame =  self.chatMsgs[indexPath.row] as! YQChatFrame
        return chatFrame.cellH!
    }
    
   // 自定义inputView
    func addChatView(_ chatView:YQChattView){
       
        self.view.addSubview(chatView)
    }
    
    // 代码创建 tableView
    func addTableView(_ tableView:UITableView){

        // 取消分割线
//      tableView.separatorStyle = .none
        self.view.addSubview(tableView)
    }
    
    // 监听 键盘的弹出
    func yq_addKeyboardObserver(){
        NotificationCenter.default.addObserver(forName:Notification.Name.UIKeyboardWillChangeFrame, object: nil, queue:OperationQueue.main) { (noti ) in
          
            let endY = (noti.userInfo![UIKeyboardFrameEndUserInfoKey] as! CGRect).origin.y
            let duration = noti.userInfo![UIKeyboardAnimationDurationUserInfoKey] as! TimeInterval
          
            let x:CGFloat = 0
            let y:CGFloat = endY - self.view.bounds.size.height
            let width:CGFloat = self.view.bounds.size.width
            let height:CGFloat = self.view.bounds.size.height
            self.view.frame = CGRect(x: x, y: y, width: width, height: height)
            // 强制布局
            UIView.animate(withDuration: duration, delay: 0, options: UIViewAnimationOptions.curveEaseIn , animations: {
                // 刷新布局
                self.view.layoutIfNeeded()
            }, completion: nil )
        }
    }
    
    // 刷新消息 -->获取消息
    func yq_reloadChatMessages(){
        self.chatMsgs.removeAllObjects()
        // 获取会话
        let conversation : EMConversation = EMClient.shared().chatManager.getConversation("1"
            , type: EMConversationTypeChat, createIfNotExist: true)

        let user = self.buddy!
        print("self.buddy == \(user)")
        //FIXME: 这里导致reload的消息都是好友1的消息 （self.buddy不能实时的变化）
        // 从服务器获取会话消息
        conversation.loadMessages(with: EMMessageBodyTypeText, timestamp: 0, count: 300  , fromUser: self.buddy, searchDirection: EMMessageSearchDirectionDown) { (messages, error ) in
        
            //TODO: 这里的步骤很重要
            let msgs:[EMMessage] = messages as! [EMMessage]
            var preTime : Int64 = 0
            // 遍历服务器获取的消息数据
            for emsg in msgs  {
                // 分级的对模型赋值
                if self.chatMsgs.count != 0 { // preTime 赋值
                    let preChatFrame : YQChatFrame = self.chatMsgs.lastObject as! YQChatFrame
                    preTime = (preChatFrame.chat?.emsg?.timestamp)!
                }
                let chat = YQChat.createObjectChatWith(preTime, emsg)
                let chatFrame:YQChatFrame = YQChatFrame()
                chatFrame.chat = chat
                // 添加数据
                self.chatMsgs.add(chatFrame)
            }
            // 刷新表格
            self.tableView?.reloadData()
            
            // 滚动到最下面
            self.scrollToBottom(self.tableView!, animated: true)
        }
    }
    
    // 键盘点击 return -->发送消息
    func textFieldShouldReturn(_ textField: UITextField) -> Bool {
        // 文本
        let body = EMTextMessageBody(text: textField.text)
        // 当前登录账号
        let from = EMClient.shared().currentUsername
       
        // 消息
        let message : EMMessage = EMMessage.init(conversationID: "1", from: from!, to: self.buddy, body: body, ext: nil)
        // 消息类型
        message.chatType = EMChatTypeChat // 单聊消息
        // 发送消息
        EMClient.shared().chatManager.send(message, progress: nil) { (message , error ) in
            if (error == nil){
                print("消息发送成功")
            }

            textField.text = nil
//            textField.resignFirstResponder()

            // 刷新聊天界面
            self.yq_reloadChatMessages()
        }
        return true
    }
}

//MARK: 类扩展
extension YQChatViewController:EMChatManagerDelegate {
    // MARK:scroll拖动 结束编辑状态
    func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
        print("scrollViewWillBeginDragging")
       
        self.chatView?.textField.endEditing(true)
    }
    
    // MARK:tableView 上按钮（点击）
    func btnclick(){
        print("tableView聊天界面--btnclick")
        self.chatView?.textField.endEditing(true)
   }
    
    // 滚动到最新消息位置
    func scrollToBottom(_ scrollView:UIScrollView,animated:Bool) {
        //FIXME: 之前用到contentSize 和 bounds 的高度差来移动,最新的数据总是会在下一次才上移
        if self.chatMsgs.count == 0 {
            return
        }
        
        let lastIndexPath =  IndexPath(row: self.chatMsgs.count - 1, section: 0)
        self.tableView?.scrollToRow(at: lastIndexPath, at: UITableViewScrollPosition.middle, animated: true)
      
        //TODO: 滚动到最下面界面不友好,每次都是晃眼睛的刷新
    }

    /// EMMchatManagerDelegate
   
    // 收到新消息
    func messagesDidReceive(_ aMessages: [Any]!) {

        let emsg =  aMessages.last as! EMMessage
        self.buddy = emsg.from
        self.yq_reloadChatMessages()
    }
        
    
}

